package com.example.amoxicilin.null_test.main;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.amoxicilin.null_test.R;
import com.example.amoxicilin.null_test.domain.Status;
import com.example.amoxicilin.null_test.tools.FileUpload;
import com.example.amoxicilin.null_test.tools.HttpUtils;
import com.example.amoxicilin.null_test.tools.JsonTools;
import com.example.amoxicilin.null_test.tools.ReplaceBlank;
import com.example.amoxicilin.null_test.tools.RichText.FileUtils;
import com.example.amoxicilin.null_test.tools.RichText.InterceptLinearLayout;
import com.example.amoxicilin.null_test.tools.RichText.RichTextEditor;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AskActivity extends AppCompatActivity implements View.OnClickListener {

    private int usernumber;
    private String title, content;
    private CheckBox art;
    private CheckBox fl;
    private CheckBox cs;
    private CheckBox law;
    private CheckBox ce;
    private CheckBox sport;
    private CheckBox ecnmy;
    private CheckBox elctrn;
    private String htmlString = "";
    int label1, label2;
    int count = 0;
    String isChecked = "";
    final List<CheckBox> checkBoxList = new ArrayList<CheckBox>();

    private final int REQUEST_CODE_CAPTURE_CAMEIA = 100;
    private final int REQUEST_CODE_PICK_IMAGE = 200;
    private final String TAG = "RichTextActivity";
    private Context context;
    private LinearLayout line_rootView, line_addImg;
    private InterceptLinearLayout line_intercept;
    private RichTextEditor richText;
    private EditText et_name;
    private FloatingActionButton question_fab;

    private boolean isKeyBoardUp, isEditTouch;// 判断软键盘的显示与隐藏
    private File mCameraImageFile;// 照相机拍照得到的图片
    private FileUtils mFileUtils;
    private String ROLE = "add";// 当前页面是新增还是查看详情 add/modify


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Bundle bundle = getIntent().getExtras();
        usernumber = bundle.getInt("usernumber");


        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                        | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        context = this;
        init();

    }

    private void init() {
        if (getIntent() != null)
            ROLE = getIntent().getStringExtra("role");
        mFileUtils = new FileUtils(context);
        art = (CheckBox) findViewById(R.id.ask_art);
        fl = (CheckBox) findViewById(R.id.ask_fl);
        cs = (CheckBox) findViewById(R.id.ask_cs);
        law = (CheckBox) findViewById(R.id.ask_law);
        ce = (CheckBox) findViewById(R.id.ask_ce);
        sport = (CheckBox) findViewById(R.id.ask_sport);
        ecnmy = (CheckBox) findViewById(R.id.ask_ecnmy);
        elctrn = (CheckBox) findViewById(R.id.ask_elctrn);
        line_addImg = (LinearLayout) findViewById(R.id.line_addImg);
        line_rootView = (LinearLayout) findViewById(R.id.line_rootView);
        line_intercept = (InterceptLinearLayout) findViewById(R.id.line_intercept);
        question_fab = (FloatingActionButton) findViewById(R.id.question_submit_fab);
        question_fab.setOnClickListener(this);
        et_name = (EditText) findViewById(R.id.et_name);
        richText = (RichTextEditor) findViewById(R.id.richText);
        checkBoxList.add(art);
        checkBoxList.add(fl);
        checkBoxList.add(cs);
        checkBoxList.add(law);
        checkBoxList.add(ce);
        checkBoxList.add(sport);
        checkBoxList.add(ecnmy);
        checkBoxList.add(elctrn);
        initRichEdit();
    }

    private void initRichEdit() {
        ImageView img_addPicture, img_takePicture;
        img_addPicture = (ImageView) line_addImg
                .findViewById(R.id.img_addPicture);
        img_addPicture.setOnClickListener(this);
        img_takePicture = (ImageView) line_addImg
                .findViewById(R.id.img_takePicture);
        img_takePicture.setOnClickListener(this);

        et_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isEditTouch = false;
                    line_addImg.setVisibility(View.GONE);
                }
            }

        });
        richText.setLayoutClickListener(new RichTextEditor.LayoutClickListener() {
            @Override
            public void layoutClick() {
                isEditTouch = true;
                line_addImg.setVisibility(View.VISIBLE);
            }
        });

        line_rootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int heightDiff = line_rootView.getRootView()
                                .getHeight() - line_rootView.getHeight();
                        if (isEditTouch) {
                            if (heightDiff > 500) {// 大小超过500时，一般为显示虚拟键盘事件,此判断条件不唯一
                                isKeyBoardUp = true;
                                line_addImg.setVisibility(View.VISIBLE);
                            } else {
                                if (isKeyBoardUp) {
                                    isKeyBoardUp = false;
                                    isEditTouch = false;
                                    line_addImg.setVisibility(View.GONE);
                                }
                            }
                        }
                    }
                });
    }

    private void openCamera() {
        try {
            File PHOTO_DIR = new File(mFileUtils.getStorageDirectory());
            if (!PHOTO_DIR.exists())
                PHOTO_DIR.mkdirs();// 创建照片的存储目录

            mCameraImageFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
            final Intent intent = getTakePickIntent(mCameraImageFile);
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
        } catch (ActivityNotFoundException e) {
        }
    }

    private Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 用当前时间给取得的图片命名
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyy_MM_dd_HH_mm_ss");
        return dateFormat.format(date) + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            richText.insertImage(mFileUtils.getFilePathFromUri(uri));
        } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA
                && resultCode == Activity.RESULT_OK) {
            richText.insertImage(mCameraImageFile.getAbsolutePath());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFileUtils.deleteRichTextImage();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.question_submit_fab:
                String uploadpath = "http://120.24.94.172/JsonTestServer/jsonTest?type1=getNextQuestion";
                String getId = HttpUtils.getJsonContent(uploadpath);
                int id = Integer.parseInt(getId);
                List<String> temp = richText.PicUploader();
                for (int i = 0; i < temp.size(); i++) {
                    String test = "";
                    test = FileUpload.UpLoadFile(temp.get(i), "question", id);
                    Status uploadstatus = JsonTools.getStatus("status", test);
                    if (uploadstatus.getStatusId() == 1) {
                        Log.i(TAG, "Success" + i);
                    }
                }//上传图片
                List<RichTextEditor.EditData> editData = richText.buildEditData();
                for (int i = 0; i < editData.size(); i++) {
                    if (editData.get(i).inputStr != null)
                        htmlString = htmlString + "<p>" + editData.get(i).inputStr + "</p>";
                    else
                        htmlString = htmlString + "<img src=\"http://120.24.94.172/JsonTestServer/upload/question/" +
                                id + "/" +
                                getFileName(editData.get(i).imagePath) + "\" /> ";
                }//整合html


                title = et_name.getText().toString();
                String contentString=ReplaceBlank.replaceAllBlank(htmlString);
                Log.i("hello",htmlString);
                   for (int i=0; i<checkBoxList.size() ; i++) {
                       if(checkBoxList.get(i).isChecked()) {
                           isChecked = ""+isChecked + String.valueOf(i+1);
                           count++;
                           if(count > 2) {
                               final android.support.v7.app.AlertDialog alertDialog = new android.support.v7.app.AlertDialog.Builder(AskActivity.this).create();
                               alertDialog.setCancelable(false);
                               alertDialog.setTitle("错误");
                               alertDialog.setMessage("选择的标签数不能超过2个");
                               alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                                           @Override
                                           public void onClick(DialogInterface dialog, int which) {
                                               alertDialog.cancel();
                                           }
                                       }
                               );
                               alertDialog.show();
                               isChecked = "";
                               break;
                           }
                       }
                   }
                label1 = (int) isChecked.charAt(0)-48;
                label2 = (int) isChecked.charAt(1)-48;

                String submitpath = "http://120.24.94.172/JsonTestServer/jsonTest?" +
                        "type1=insert&type2=question&name=" +
                        title + "&label1=" + label1 + "&label2=" + label2 + "&content2=" + contentString +
                        "&pnumber=" + usernumber + "&upvote=0";
                String submitString = HttpUtils.getJsonContent(submitpath);

                final Status status = JsonTools.getStatus("status", submitString);

                Log.i("path", submitpath);
                Log.i("status", ""+status.getStatusId());

                new AlertDialog.Builder(AskActivity.this)
                        .setTitle("系统消息")
                        .setMessage("确定要提交吗？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (status.getStatusId() == 1) {
                                    new AlertDialog.Builder(AskActivity.this)
                                            .setTitle("系统消息")
                                            .setMessage("提交成功！").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).show();
                                } else {
                                    new AlertDialog.Builder(AskActivity.this)
                                            .setTitle("系统消息")
                                            .setMessage("提交失败！").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .show();
                break;
            case R.id.img_addPicture:
                // 打开系统相册
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");// 相片类型
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                break;
            case R.id.img_takePicture:
                // 打开相机
                openCamera();
                break;

        }
    }


    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.length();
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }



}
